#include<stdio.h>
#include<stdlib.h>
#include"mystdio.h"
#include<string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>


myFILE* my_fopen(const char* pathname,const char* mode)
{
    int fd = 0;
    umask(0);
    if(strcmp(mode,"r")==0)
    {
        fd = open(pathname,O_RDONLY);
    }
    else if(strcmp(mode,"w")==0)
    {
        fd = open(pathname,O_CREAT|O_WRONLY|O_TRUNC,0666);
    }
    else if(strcmp(mode,"a")==0)
    {
        fd = open(pathname,O_CREAT|O_WRONLY|O_APPEND,0666);
    }
    else
    {
        return NULL;
    }

    if(fd<0)
    {
        return NULL;
    }
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(fp==NULL) return NULL;
    fp->fileno=fd;
    fp->cap=SIZE;
    fp->flush_mode=LINE_FLUSH;
    fp->pos = 0;

    return fp;
}

void my_flush(myFILE* fp)
{
    if(fp->pos==0) return ;
    write(fp->fileno,fp->buffer,fp->pos);
    fp->pos=0;
}
int my_fwrite(myFILE* fp,const char* s,int size)
{
    memcpy(fp->buffer+fp->pos,s,size);
    fp->pos+=size;
    if(fp->flush_mode==LINE_FLUSH && fp->buffer[fp->pos-1]=='\n')
    {
        my_flush(fp);
    }
    //下面可以判断全刷新等等
    if(fp->flush_mode==FULL_FLUSH && fp->pos == fp->cap)
    {
        my_flush(fp);
    }
    return size; 

}
void my_fclose(myFILE* fp)
{
    my_flush(fp);
    close(fp->fileno);
    free(fp);
}





